// 判断用户是否登录
// 从cookie中获取存起来的用户名
var username=getCookie('username')
if(username){
    $('.pagetop-content p').html(`
	汪，欢迎来天猫~
        <a href="userInfo.html" target="_Blank"  style="font-size:14px;">${username}</a> 用户
		<a onclick="logout()" target="_Blank">退出登录</a>
    `)
}

// 定义退出函数
function logout(){
    // 询问层
    layer.confirm('你确定要退出吗？', {
        btn: ['残忍离开', '考虑一下']
    }, function(){
        // 将内容还原
        $('.pagetop-content p').html(`
		汪，欢迎来天猫
			<a href="login.html" target="_Blank">请登录</a>
			<a href="register.html" target="_Blank">免费注册</a>
		`)
        // 删除cookie
        removeCookie('username')
        removeCookie('userId')
        localStorage.removeItem('token')
        layer.msg('退出成功', {
            icon: 1,
            time: 1500
        })
    }, function(){
        layer.msg('取消成功', {
            icon: 1,
            time: 1500
        })
    })
}
// 先获取地址栏中的商品id
var reg = /id=([^&]+)/
var arr = location.search.match(reg)
var goodsId = ''
if(arr && arr[1]){
    // 获取到商品id
    goodsId = arr[1]
    // 发送商品详情的请求
    getData()
}else{
    layer.msg('非法访问！', {
        icon: 2,
        time: 2000
    }, function(){
        location.href = 'shopList.html'
    })
}

// 发送请求的函数
function getData(){
    $.get('http://localhost:8888/goods/item?id='+goodsId).then(res => {
        console.log(res);
        if(res.code === 1){
			$('.zoom .middle>img').attr('src', res.info.img_big_logo)
            var imgHTML = ''
            for(var i=0;i<$('.zoom .small img').length;i++){
                imgHTML += `
                    <li class="active">
                    <img src="${res.info.img_big_logo}" alt="">
                    </li>
                `
            }
            $('.zoom .small').html(imgHTML)
            $('.zoom .middle .big img').attr('src', res.info.img_big_logo)

			// 渲染商品数据 开启放大镜
            var t = new Zoom()
            t.move()

            // 渲染商品数据
            $('.showShop-content>h1').text(res.info.title)
            $('.oldPice s').text(res.info.price)
            $('.nowPice>span').text(res.info.current_price)
            $('.changeNum>p>span').text(res.info.current_price)

            // 数量加减
            addNumber()

            // 加入购物车
            addCart()

            
        }else{
            layer.msg('非法访问！', {
				icon: 2,
				time: 2000
			}, function(){
				location.href = 'shopList.html'
			})
        }

    })
}
//放大镜功能
function Zoom(){
    this.middle=document.querySelector('.middle')
    this.big=document.querySelector('.big')
    this.shade=document.querySelector('.shade')
    this.small=document.querySelector('.small')
    this.bigImg=document.querySelector('.big img')
    this.middleImg=document.querySelector('.middle>img')
}
Zoom.prototype.move=function(){
    //点击小图切换选框
    for(let i=0;i<this.small.children.length;i++){
        this.small.children[i].onclick=()=>{
            for(let j=0;j<this.small.children.length;j++){
                this.small.children[j].className=''
            }
            this.small.children[i].className='active'
            var path = this.small.children[i].firstElementChild.getAttribute('src')
            this.middleImg.setAttribute('src',path)
            this.bigImg.setAttribute('src',path)
        }            
    }
    //鼠标移动遮罩跟随
    this.middle.onmouseover=()=>{
        this.big.style.display='block'
        this.shade.style.display='block'
        this.middle.onmousemove=()=>{
            // 鼠标移入大图消失
            var e = window.event
            var x = e.pageX
            var y = e.pageY
            var l = x - this.shade.clientWidth/2-this.middle.offsetLeft
            var t = y - this.shade.clientHeight/2-this.middle.offsetTop
            //限制遮罩运动范围
            if(l<0) l=0
            if(t<0) t=0
            if(l>this.middle.offsetWidth-this.shade.offsetWidth) l=this.middle.offsetWidth-this.shade.offsetWidth
            if(t>this.middle.offsetHeight-this.shade.offsetHeight) t=this.middle.offsetHeight-this.shade.offsetHeight
            this.shade.style.top=t+'px'
            this.shade.style.left=l+'px'
            //鼠标移动大图大小跟随变化
            this.bigImg.style.left=-l/this.middle.offsetWidth*this.bigImg.offsetWidth+'px'
            this.bigImg.style.top=-t/this.middle.offsetHeight*this.bigImg.offsetHeight+'px'
        }
                //鼠标划出大图消失
        this.middle.onmouseout=()=>{
            this.shade.style.display='none'
            this.big.style.display='none'
        }
    }
}

// 数量加减
function addNumber(){
    // ＋
    $('#add').click(function () {
		var nowNum = $('#buyNum').val()
		$('#buyNum').attr('value', nowNum * 1 + 1)
		update();
	})
    // -
	$('#minus').click(function () {
		var nowNum = $('#buyNum').val()
		if (nowNum == 1) return;
		$('#buyNum').attr('value', nowNum - 1)
		update();
	})
}
// 数据更新
function update() {
    var nowNum = $('#buyNum').val();
    var nowPrice = $(".nowPice").find('span').text();
    $('.oldPice s').text(nowPrice * 1 + 500);
    var SumPrice = (nowNum * nowPrice).toFixed(2);
    $('.changeNum p span').text(SumPrice);
    $('#huabei-item-one').find('b').text((SumPrice / 2.9).toFixed(1))
    $('#huabei-item-two').find('b').text((SumPrice / 5.5).toFixed(1))
    $('#huabei-item-three').find('b').text((SumPrice / 11).toFixed(1))
    // console.log(SumPrice)
}

// 加入购物车
function addCart(){
    // 点击加入购物车按钮
    $('#addCartBut').click(function(){
        // 判断用户是否登录
        if(!username){
            layer.msg('请先登录！', {
                icon: 2,
                time: 2000
            }, function(){
                // 强制跳转到登录页面
                location.href = 'login.html?callback='+location.href
            })
        }else{
            // 已经登录了
            // 发送请求添加购物车
            $.ajax({
                url: 'http://localhost:8888/cart/add',
                method: 'post',
                data: {
                    goodsId,
                    id: getCookie('userId')
                },
                headers: {
                    'authorization': localStorage.getItem('token') || ''
                }
            }).then(res => {
                // console.log(res);
                if(res.code === 1){
                    layer.msg(res.message, {
                        icon: 1,
                        time: 2000
                    })
                }else{
                    layer.msg('加入购物车失败，请刷新重试！', {
                        icon: 2,
                        time: 2000
                    })
                }
            })
        }
    })
    $('#buyNow').click(function(){
        location.href='cart.html'
    })
}